package czx.wt.filter;

import czx.wt.util.HttpUtil;
import czx.wt.util.SsoClientUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ChenZhiXiang
 * @version 1.0.0
 * @Description TODO
 * @createTime 2018年12月27日 20:38:00
 */
@WebFilter(filterName = "loginFilter",urlPatterns = "/*")
@Order(1)
public class LoginFilter implements Filter {

    private static final Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        logger.info("client01过滤器开始...............");
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        HttpSession session = request.getSession();

        logger.info("判断是否有局部会话");
        Boolean isLogin = (Boolean) session.getAttribute("isLogin");
        if (null != isLogin && isLogin){
            logger.info("isLogin"+isLogin+"，有局部会话，放行。。。。");
            filterChain.doFilter(request,response);
            return;
        }
        logger.info("判断地址栏中是否有token参数");
        String token= request.getParameter("token");
        if (StringUtils.isNoneBlank(token)){
            //token信息不为null,说明地址中包含了token,拥有令牌.
            //判断token信息是否由认证中心产生的.验证地址为:http://www.server.com:8080/verify
            String httpUrl = SsoClientUtil.SERVER_URL_PREFIX+"/verify";
            Map<String,String> params = new HashMap<>();
            logger.info("把客户端的token的信息传递给统一认证中心进行校验"+params.toString());
            params.put("token",token);
            try {
                String isVerify = HttpUtil.sendHttpRequest(httpUrl,params);
                if (isVerify.equals("true") && null != isVerify){
                    logger.info("token验证通过，说明token是统一认证中心产生的");
                    logger.info("创建局部会话");
                    session.setAttribute("isLogin",true);
                    logger.info("放行该请求");
                    filterChain.doFilter(request,response);
                    return;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        logger.info("没有token，跳转到统一认证中心");
        SsoClientUtil.redirectToSSOURL(request,response);
    }

    @Override
    public void destroy() {

    }
}
